#include "msg_deal.h"

const uint8_t reply_head[] =   {0x77, 0xBB};

const char myth_key[] = "uestc8020";


static inline uint8_t cs_creat(uint8_t *buf,uint8_t len)
{
    int sum = 0;
    for(int i = 0;i<len;i++){
        sum += buf[i];
    }
    return sum;
}

static void pack_send_msg(uint8_t* payload,uint16_t load_len,uint8_t cmd)
{
    uint8_t packet[sizeof(reply_head)+load_len+4];// cmd hh ll cs

    uint8_t head_len = sizeof(reply_head);
    //回复的包头
    memcpy(packet,reply_head,head_len);

    packet[head_len] = cmd;

    packet[head_len+1] = sizeof(packet)&0xff;
    packet[head_len+2] = (sizeof(packet)>>8)&0xff;

    if(payload)
    {
        memcpy(packet+head_len+3,payload,load_len);
    }

    packet[head_len+3+load_len] = cs_creat(packet,head_len+3+load_len);

    /*数据放入缓冲*/
    extern void put_pkg_to_ringbuf(uint8_t *pkg, uint16_t len);

    put_pkg_to_ringbuf(packet, sizeof(packet));
}

void usbh_set_key(uint8_t* data,uint16_t len)
{
    USB_LOG_RAW("usbh_set_key\r\n");
    pack_send_msg(NULL,0,SET_KEY);
}

void usbh_get_key(uint8_t* data,uint16_t len)
{
    USB_LOG_RAW("usbh_get_key\r\n");
    uint8_t key[20] = {0};
    memcpy(key,myth_key,sizeof(myth_key));
    pack_send_msg(key,sizeof(myth_key),GET_KEY);
}

void usbh_get_logs(uint8_t* data,uint16_t len)
{
    USB_LOG_RAW("usbh_get_logs\r\n");
    pack_send_msg(NULL,0,GET_LOGS);
}


const cmd_msg_list usb_msg_func_list[] = {
    {SET_KEY,       usbh_set_key},
    {GET_KEY,       usbh_get_key},
    {GET_LOGS,      usbh_get_logs},
};

void usb_recv_msg_deal(uint8_t* data,uint16_t len)
{
    for(int i = 0;i < sizeof(usb_msg_func_list)/sizeof(cmd_msg_list);i++)
    {
        if(data[0] == usb_msg_func_list[i].cmd)
        {
            usb_msg_func_list[i].func(data+1,len-1);
            break;
        }
    }
}

// 0x77 0xAA 0x01 0x00 0x08 0x00 0x0C 0x36